package com.ysalliance.getFan.organization.ui;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.ysalliance.getFan.organization.Bean.ClassBean;
import com.ysalliance.getFan.organization.Bean.OrganizationBean;
import com.ysalliance.getFan.organization.Bean.UserBean;
import com.ysalliance.getFan.organization.LucasUtil;
import com.ysalliance.getFan.organization.R;
import com.ysalliance.getFan.organization.adapter.ClassroomAdapter;
import com.ysalliance.getFan.organization.myview.FunButton;
import com.ysalliance.getFan.organization.network.Network;
import com.ysalliance.getFan.organization.ui.base.LucasBaseActivity;
import com.ysalliance.getFan.organization.ui.h5.CommonH5Activity;
import com.ysalliance.getFan.organization.ui.login.LoginActivity;

import org.json.JSONObject;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static com.ysalliance.getFan.organization.FanerConstant.ENTER;
import static com.ysalliance.getFan.organization.FanerConstant.SET_CLASS_NAME;


/**
 * 入驻页面
 * @author lucas
 * created at 2020-02-24 14:54
 */
public class OrganizationActivity extends LucasBaseActivity {

    //用户协议
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.funbt_enter)
    FunButton funbt_enter;    //立即入驻
    @BindView(R.id.tv_tag)
    TextView tv_tag;   //TextView提示
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.img_class_manager)
    ImageView img_class_manager;

    private CustomPopWindow mCustomPopWindow;

    private ClassroomAdapter classroomAdapter;

    public List<ClassBean> list = new ArrayList<>();

    public OrganizationBean organizationBean;

    private long firstTime;// 记录点击返回时第一次的时间毫秒值

    @Override
    public int bindContentView() {
        return R.layout.activity_organization;
    }

    @Override
    public void afterView() {
        super.afterView();


        funbt_enter.setVisibility(View.INVISIBLE);
        tv_tag.setVisibility(View.INVISIBLE);


        recycler.setVisibility(View.INVISIBLE);
        //唱段列表Adapter初始化
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(linearLayoutManager);
        //设置列表默认动画效果
        recycler.setItemAnimator(new DefaultItemAnimator());
        classroomAdapter = new ClassroomAdapter(R.layout.item_classroom, list);
        recycler.setAdapter(classroomAdapter);
        //列表点击事件
        classroomAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(Utils.getApp(), ClassroomActivity.class);
                intent.putExtra("class_info", list.get(position));
                ActivityUtils.startActivity(intent);
            }
        });


        initClick();

    }



    @Override
    protected void onResume() {
        super.onResume();
        get_organization();
    }

    public void initClick() {


        img_class_manager.setOnClickListener(v->{
            showPopMenu(img_class_manager);
        });




    }






    /** popupwindow  */
    private void showPopMenu(View view) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_menu_organization, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int  mShowMorePopupWindowWidth = -contentView .getMeasuredWidth();
        int  mShowMorePopupWindowHeight = -contentView .getMeasuredHeight();


        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .create()
                .showAsDropDown(view,mShowMorePopupWindowWidth + 100,0);
    }
    private void handleLogic(View contentView){
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCustomPopWindow!=null){
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()){
                    case R.id.menu1_create_class:
                        //创建班级
                        //0未入住;1:已通过 2:未通过 3:已撤销
                        if(organizationBean.getStatus()==1){
                            Intent intent = new Intent(Utils.getApp(), EditTextOneActivity.class);
                            intent.putExtra("class", SET_CLASS_NAME);
                            intent.putExtra("organization", organizationBean);
                            ActivityUtils.startActivity(intent);
                        }else if(organizationBean.getStatus()==0){
                            ToastUtils.showShort("您还未入驻");
                        }else if(organizationBean.getStatus()==2){
                            ToastUtils.showShort("您的入驻申请还未通过");
                        }else if(organizationBean.getStatus()==3){
                            ToastUtils.showShort("您的入驻申请已被撤销");
                        }

                        break;
                    case R.id.menu2_logout:
                        //退出登录
                        LitePal.deleteAll(UserBean.class);
                        ActivityUtils.startActivity(LoginActivity.class);
                        finish();
                        break;

                }
            }
        };
        contentView.findViewById(R.id.menu1_create_class).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2_logout).setOnClickListener(listener);
    }



    /**  获取组织机构   */
    public void get_organization(){

        disposable = Network.getUtilApi()
                .get_organization()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("获取组织结构的返回", res);

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){

                            organizationBean = new Gson().fromJson( jsonObject.optString("data"), OrganizationBean.class);
                            organizationBean.save();
                            freshUI(organizationBean);

                        }else {
                            ToastUtils.showShort(jsonObject.optString("message"));
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    private void freshUI(OrganizationBean organizationBean) {
        //0未入住;1:已通过 2:未通过 3:已撤销
        if(organizationBean.getStatus() == 0){

            funbt_enter.setVisibility(View.VISIBLE);
            tv_tag.setVisibility(View.VISIBLE);

            //只登陆 没有申请入驻
            //funbt点击事件  立即入驻
            funbt_enter.setOnClickListener(v->{
                Intent intent = new Intent(Utils.getApp(), CommonH5Activity.class);
                intent.putExtra("url", ENTER);
                ActivityUtils.startActivity(intent);
            });
        }else if(organizationBean.getStatus() == 1){
            if(organizationBean.getClassX().size()<1){
                //没有任何班级

                funbt_enter.setVisibility(View.VISIBLE);
                tv_tag.setVisibility(View.VISIBLE);

                tv_title.setText(organizationBean.getName());  //标题
                tv_tag.setText("您还未创建班级");
                funbt_enter.setTvTag("创建班级");
                funbt_enter.setFunbt_Img(R.mipmap.funbt_add);
                //funbt点击事件  创建班级
                funbt_enter.setOnClickListener(v->{
                    Intent intent = new Intent(Utils.getApp(), EditTextOneActivity.class);
                    intent.putExtra("class", SET_CLASS_NAME);
                    intent.putExtra("organization", organizationBean);
                    ActivityUtils.startActivity(intent);
                });
            }else {
                //有班级信息
                tv_title.setText(organizationBean.getName());  //标题
                funbt_enter.setVisibility(View.GONE);
                tv_tag.setVisibility(View.GONE);
                recycler.setVisibility(View.VISIBLE);
                list.clear();
                list.addAll(organizationBean.getClassX());
                classroomAdapter.notifyDataSetChanged();
            }

        }


    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){// 点击了返回按键
            exitApp(2000);// 退出应用
            return true;// 返回true，防止该事件继续向下传播
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出应用
     * @param timeInterval 设置第二次点击退出的时间间隔
     */
    private void exitApp(long timeInterval) {
        // 第一次肯定会进入到if判断里面，然后把firstTime重新赋值当前的系统时间
        // 然后点击第二次的时候，当点击间隔时间小于2s，那么退出应用；反之不退出应用
        if(System.currentTimeMillis() - firstTime >= timeInterval){
            ToastUtils.showShort( "再按一次退出程序");
            firstTime = System.currentTimeMillis();
        }else {
            finish();// 销毁当前activity
            System.exit(0);// 完全退出应用
        }
    }


}
